/**
 * <p>Title: </p>
 * <p>Description: </p>
 * <p>Copyright: Copyright (c) 2006</p>
 * <p>CreateTime: 2006-3-28 </p>
 * @author pengz
 * @version 1.0
 */

package cn.agiledata.bank.myspace.action;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import cn.agiledata.bank.audit.service.AuditService;
import cn.agiledata.bank.common.bean.SelectBean;
import cn.agiledata.bank.common.dao.AccountTemplate;
import cn.agiledata.bank.common.dao.TransactionTemplate;
import cn.agiledata.bank.common.service.ICommonService;
import cn.agiledata.bank.common.service.NotifyUtil;
import cn.agiledata.bank.common.servlet.InitForString;
import cn.agiledata.bank.common.util.Constant;
import cn.agiledata.bank.common.util.DateUtil;
import cn.agiledata.bank.common.util.PageBean;
import cn.agiledata.bank.common.util.StringUtil;
import cn.agiledata.bank.common.util.WeatherUtil;
import cn.agiledata.bank.hibernateBean.Account;
import cn.agiledata.bank.hibernateBean.AuditOperandType;
import cn.agiledata.bank.hibernateBean.AuditOperation;
import cn.agiledata.bank.hibernateBean.CityInfo;
import cn.agiledata.bank.hibernateBean.EsPrePayTrans;
import cn.agiledata.bank.hibernateBean.HistoryAuditOperation;
import cn.agiledata.bank.hibernateBean.Sysbook;
import cn.agiledata.bank.hibernateBean.Transaction;
import cn.agiledata.bank.myspace.bean.AccountHisQueryDetailBean;
import cn.agiledata.bank.transaction.audit.service.EsPrePayTransService;
import cn.agiledata.bank.transaction.form.EsAuditHistory;
import cn.agiledata.bank.transaction.form.FillMoneyForm;
import com.vnv.infrastructure.action.IPBBaseDynaForm;
import com.vnv.infrastructure.exception.IPBException;
import com.vnv.infrastructure.logic.IPBAppFactory;

public class AccountQueryAction extends AbstractMySpaceAction {

	public ActionForward accountQuery(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws IPBException, Exception {

		return mapping.findForward("queryList");
	}
	public ICommonService getCommonService() {
		ICommonService service = (ICommonService) IPBAppFactory
				.getObj(ICommonService.SERVICE_NAME);
		return service;
	}
	private EsPrePayTransService getEsPrePayTransService() throws IPBException {
		return (EsPrePayTransService) IPBAppFactory
				.getObj("EsPrePayTransService");
	}
	private AuditService getAuditService() throws IPBException {
		return (AuditService) IPBAppFactory.getObj("auditService");
	}
	/**
	 * 账户历史查询列表
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws IPBException
	 * @throws Exception
	 */
	public ActionForward accountQueryHis(ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws IPBException, Exception {

		IPBBaseDynaForm dynaForm = (IPBBaseDynaForm) form;
		List listId =InitForString.getListId("ACTION_TYPE");
		List listName=InitForString.getListName("ACTION_TYPE");
		List actionType = new ArrayList();
		List actionTypePersonal = new ArrayList();
		for (int j = 0; j < listId.size(); j++) {
			//3.账户间交易
			//5.冲正
			//6.银行卡付款给对方账户
			//12.电话银行付款给对方账户
			//18.B2B网上银行付款
			//19.卡付款
			//20.退款
			SelectBean selectBean = null;
			if(listId.get(j).equals(new Long(Constant.ACTION_TYPE_C))
					||listId.get(j).equals(new Long(Constant.ACTION_TYPE_E))
					||listId.get(j).equals(new Long(Constant.ACTION_TYPE_F))
					||listId.get(j).equals(new Long(Constant.ACTION_TYPE_L))
					||listId.get(j).equals(new Long(Constant.ACTION_TYPE_P))
					||listId.get(j).equals(new Long(Constant.ACTION_TYPE_Q))
					||listId.get(j).equals(new Long(Constant.ACTION_TYPE_R))){
				selectBean = new SelectBean((Long)listId.get(j), (String)listName.get(j));
			}
			if (selectBean != null)actionType.add(selectBean);
			selectBean = null;
			
			if (!listId.get(j).equals(new Long(Constant.ACTION_TYPE_A))
					&& !listId.get(j).equals(new Long(Constant.ACTION_TYPE_K))
					&& !listId.get(j).equals(new Long(Constant.ACTION_TYPE_X))) {
				selectBean = new SelectBean((Long)listId.get(j), (String)listName.get(j));
			}
			if (selectBean != null)actionTypePersonal.add(selectBean);
			selectBean = null;
		}
		request.setAttribute("ACTION_TYPE_PERSONAL", actionTypePersonal);
		request.setAttribute("ACTION_TYPE", actionType);
		int startPage = 1;
		
		if (dynaForm.get("startPage") != null
				&& !dynaForm.get("startPage").equals("")) {
			startPage = Integer.parseInt((String) dynaForm.get("startPage"));
		}
		if ((!StringUtil.isStrEmpty(dynaForm.get("beginDate").toString()))
				&&(!StringUtil.isStrEmpty(dynaForm.get("endDate").toString()))) {
			if (DateUtil.string2Date(dynaForm.get("beginDate").toString()).after(DateUtil.string2Date(
					dynaForm.getString("endDate").toString()))) {
				//dynaForm.getMap().clear();
				dynaForm.getMap().put("errorMsg", "您输入的查询截至日期小于查询开始日期，请重新输入");
			}
		}
		String accountId = String.valueOf(WeatherUtil
				.getAccountIdFromSession(request));
		String accountName = WeatherUtil.getAccountNameFromSession(request);
		dynaForm.getMap().put("accountID", accountId);
		if (accountName != null) {
			dynaForm.getMap().put("accountName", accountName);
		}

		PageBean pb = getMySpaceService().getAccountHisListPageBean(
				dynaForm.getMap(), startPage, new Long(20).intValue());

		request.setAttribute("pagination", pb);
		request.setAttribute("accountID", accountId);
		Account account = getMySpaceService().getAccount(accountId);
		request.setAttribute("account", account);
		
		return mapping.findForward("queryHisList");
	}

	public ActionForward accountHisQueryDetail(ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws IPBException, Exception {
		Map m = getMap(form);
		String tid = null;
		if (m.get("transactionID") != null)
			tid = (String) m.get("tid");
		tid = request.getParameter("transactionID");
		String operate = request.getParameter("operate");
		request.setAttribute("operate", operate);
		String accountID = getAccountId(request);

		AccountHisQueryDetailBean aqb = getMySpaceService()
				.accountHisQueryDetail(tid, accountID);

		// 提现
		// FIXME 此处由于使用Long与String进行equals,所以所有的判断结果均为false zln 20080226
		if (aqb.getT().getActionType().getId().equals(Constant.ACTION_TYPE_D))
			return mapping.findForward("accountHisQueryDetail_pay");
		// 账户付款给对方银行
		if (aqb.getT().getActionType().getId().equals(Constant.ACTION_TYPE_G))
			return mapping.findForward("accountHisQueryDetail_toMan");

		else {
			if (aqb.getT().getTradeType() != null
					&& aqb.getT().getTradeType().equals(
							Constant.TRADE_TYPE_ASSURE)) {// 增加截止时间
				int[] leftTime = NotifyUtil.getPermissionLeftDHM(aqb.getT()
						.getUpdateTime(), aqb.getT().getTransStatus());
				if ((leftTime[0] == 0 && leftTime[1] == 0 && leftTime[2] == 0)
						|| leftTime[0] < 0 || leftTime[1] < 0
						|| leftTime[2] < 0) {
					/*
					 * 交易的历史查询和待处理交易使用的是同一个流程(action,.jsp)，
					 * 为与交易状态无关(难保交易状态不增加)则使用此判断以决定是否显示剩余时间
					 */} else {
					request.setAttribute("leftDays", "" + leftTime[0]);
					request.setAttribute("leftHours", "" + leftTime[1]);
					request.setAttribute("leftMinutes", "" + leftTime[2]);
					request.setAttribute("hasleft", "");
					AccountTemplate at = (AccountTemplate) IPBAppFactory
							.getObj("accountTemplate");
					Sysbook book = at.getDatePermitById(aqb.getTransStatus());

					int date = Integer.parseInt(book.getListName());
					int datetime = date / 24 / 60;
					request.setAttribute("date", datetime + "");
					Date lastdate = NotifyUtil.getPermitedEndDate(aqb.getT()
							.getUpdateTime(), aqb.getTransStatus());
					request.setAttribute("lastdate", DateUtil.date2String(
							lastdate, "yyyy-MM-dd HH:mm:ss"));
				}
			}
			request.setAttribute("aqb", aqb);

			if (aqb.getT().getActionType().getId().toString().equals(
					Constant.ACTION_TYPE_E)) {// 冲正
				// 获取关联交易的交易编号
				TransactionTemplate tt = (TransactionTemplate) IPBAppFactory
						.getObj("transactionTemplate");
				String relatingTransId = tt.getTransaction(
						aqb.getT().getRelating().toString()).getTransId();
				request.setAttribute("relatingTransId", relatingTransId);
			}

			// 审核历史
			try {
				String audited = "true";
				EsPrePayTrans esTran = getEsPrePayTransService()
						.getEsPrePayTransByTransId(aqb.getT().getTransId());
				if (esTran.getDebit().getAccount().getId().toString().equals(
						accountID)) {
					AuditOperandType auditOperandType = getAuditService()
							.getAuditOperandType(
									"ES_PRE_PAY_TRANS",
									String.valueOf(esTran.getActionType()
											.getId()));
					HistoryAuditOperation[] ho = getAuditService()
							.getHistoryAuditOperations(auditOperandType,
									esTran.getId().longValue());
					List history = new ArrayList();
					for (int i = 0; i < ho.length; i++) {
						AuditOperation type = ho[i];
						EsAuditHistory his = new EsAuditHistory(type);
						his.setUpdateUserName((getMySpaceService()
								.getOperatorById(type.getUpdateUser()))
								.getOperatorName());
						history.add(his);
					}
					request.setAttribute("history", history);
					request.setAttribute("audited", audited);
				}
			} catch (Exception e) {
				String audited = "false";
				request.setAttribute("audited", audited);
				return mapping.findForward("accountHisQueryDetail");
			}
			//审核历史
			return mapping.findForward("accountHisQueryDetail");
		}
	}



	public ActionForward getAcctBalHis(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws IPBException, Exception {
		IPBBaseDynaForm dynaForm = (IPBBaseDynaForm) form;
		int startPage = 1;
		if (dynaForm.get("startPage") != null
				&& !dynaForm.get("startPage").equals("")) {
			startPage = Integer.parseInt((String) dynaForm.get("startPage"));
		}
		String accountId = String.valueOf(WeatherUtil
				.getAccountIdFromSession(request));
		dynaForm.getMap().put("accountID", accountId);
		PageBean pb = getMySpaceService().getAcctSubHisPageBean(
				dynaForm.getMap(), startPage, new Long(20).intValue());

		request.setAttribute("pagination", pb);
		request.setAttribute("accountID", accountId);
		Account account = getMySpaceService().getAccount(accountId);

		request.setAttribute("account", account);
		return mapping.findForward("balHis");
	}
	
	public ActionForward reDownFillMoney(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response) throws Exception{
		TransactionTemplate tt = (TransactionTemplate)IPBAppFactory.getObj("transactionTemplate");
		FillMoneyForm fform = (FillMoneyForm) actionForm;
		Transaction tran = tt.getTransaction(request.getParameter("id"));
		setForm(tran,fform);
		List bankList = getCommonService().getBankList();//在跳转线下支付的时候，我们把公司可以收款的银行放入list中，传到页面
		request.setAttribute("bankList", bankList);
		request.setAttribute("bankInfo", InitForString.dataDictMap.get("BANK_INFO"));
		request.setAttribute("province", InitForString.dataDictMap.get("PROVINCE_INFO"));
		List provinceList = (List) InitForString.dataDictMap
		.get("PROVINCE_INFO");
		request.setAttribute("province", provinceList);
		List cityList = null;
		if (fform.getProvSeq() != null) {
			cityList = (List) InitForString.dataDictMap.get(fform
					.getProvSeq().toString());
			request.setAttribute("city", cityList);
		} else {
			cityList = (List) InitForString.dataDictMap
					.get(((CityInfo) provinceList.get(0)).getCityId());
			request.setAttribute("city", cityList);
		}
		if (cityList == null) {
			cityList = (List) InitForString.dataDictMap
					.get(((CityInfo) provinceList.get(0)).getCityId());
			request.setAttribute("city", cityList);
		}
		if(tran.getBankSeq()==null||(tran.getBankSeq()!=null&&tran.getBankSeq().longValue()==0)){
			request.setAttribute("tranType", "邮局汇款");
		}else{
			request.setAttribute("tranType", "银行汇款");
		}
		
		return mapping.findForward("bankAccess");
	}
	
	
	private void setForm(Transaction tran,FillMoneyForm fform){
		fform.setCreditName(tran.getCredit().getAccountName());
		fform.setOpenBank(tran.getBankSeq()+"");
		fform.setBankName(tran.getBankName());
		fform.setAccount(tran.getAmount().toString());
	    fform.setProvSeq(tran.getBankProvSeq().toString());
		fform.setCitySeq(tran.getBankCitySeq().toString());
		fform.setRemark(tran.getRemark());
		fform.setBankInfo(tran.getBankInfoSeq()+"");
		fform.setPersonName(tran.getPersonName());
		fform.setCardNo(tran.getCardNo());
	}
}